<template>
  <div class="wrapper">
    <el-container>
      <el-aside width="300px" class="aside">
        <el-button v-if="$_permisson('/core/dict/saveDictType')" type="primary" @click="showDialog('dicTypeCreate')">
          新增字典类型
        </el-button>
        <el-tree
          :data="options"
          :props="{
            children: 'children',
            value:'key',
            label:'title'
          }"
          @node-click="handleNodeClick"
        >
          <template slot-scope="{ node, data }">
            <el-row :gutter="24" class="treeItem">
              <el-col :span="12">
                <span style="vertical-align: sub;">{{ node.label }}</span>
              </el-col>
              <el-col :span="12" align="right">
                <el-button v-if="$_permisson('/core/dict/saveDictType')" type="text" @click="createTypeChildren(data)">新增下级</el-button>
                <el-button v-if="$_permisson('/core/dict/deleteDictType')" type="text" @click="removeTypeItem(data)">删除</el-button>
              </el-col>
            </el-row>
          </template>
        </el-tree>
      </el-aside>
      <el-main class="main">
        <!-- 字典类型详情 -->
        <el-row class="title">
          <el-col :span="12">
            <div class="">
              <i class="el-icon-mobile" />
              字典信息
            </div>
          </el-col>
          <el-col :span="12" class="active" align="right">
            <el-button v-if="$_permisson('/core/dict/saveDictType')&&ditTypeInfo.id" type="primary" @click="editTypeItem">修改信息</el-button>
          </el-col>
        </el-row>
        <el-row class="dicBox">
          <el-col :span="8">
            <el-col :span="5" align="center">
              名称:
            </el-col>
            <el-col :span="15">
              <div class="grid-content bg-purple">
                {{ ditTypeInfo.dictTypeName }}
              </div>
            </el-col>
          </el-col>
          <el-col :span="8">
            <el-col :span="5" align="center">
              code:
            </el-col>
            <el-col :span="15">
              <div class="grid-content bg-purple">
                {{ ditTypeInfo.dictTypeCode }}
              </div>
            </el-col>
          </el-col>
          <el-col :span="8">
            <el-col :span="5" align="center">
              状态:
            </el-col>
            <el-col :span="15">
              <div class="grid-content bg-purple">
                {{ ditTypeInfo.status }}
              </div>
            </el-col>
          </el-col>
          <el-col :span="8">
            <el-col :span="5" align="center">
              备注:
            </el-col>
            <el-col :span="15">
              <div class="grid-content bg-purple">
                {{ ditTypeInfo.note }}
              </div>
            </el-col>
          </el-col>
          <el-col :span="8">
            <el-col :span="5" align="center">
              允许删除:
            </el-col>
            <el-col :span="15">
              <div class="grid-content bg-purple">
                {{ ditTypeInfo.delEnabledStr }}
              </div>
            </el-col>
          </el-col>
          <el-col :span="8">
            <el-col :span="5" align="center">
              树形结构:
            </el-col>
            <el-col :span="15">
              <div class="grid-content bg-purple">
                {{ ditTypeInfo.isTreeStr }}
              </div>
            </el-col>
          </el-col>
        </el-row>

        <el-row :gutter="24" class="title">
          <el-col :span="12">
            <div class="">
              <i class="el-icon-coin" />
              字典列表
            </div>
          </el-col>
          <!-- <el-col :span="12" align="right" class="active">
            <el-button v-if="$_permisson('/core/dict/saveDict')" @click="showDialog()">添加字典</el-button>
          </el-col> -->
        </el-row>

        <JTable :table-list="tableList" :config="tableConfig">
          <template slot="Actions" slot-scope="{row}">
            <el-button v-if="$_permisson('/core/dict/saveDict')" type="text" @click="handleActive(row,'edit')">修改</el-button>
            <el-button v-if="$_permisson('/core/dict/saveDict')" type="text" @click="handleActive(row,'create')">新增子类</el-button>
            <el-button v-if="$_permisson('/core/dict/deleteDict')" type="text" @click="handleActive(row,'del')">删除</el-button>
          </template>
        </JTable>

      </el-main>
    </el-container>

    <el-dialog :title="dialog.title[dialog.active]" :visible.sync="dialog.dialogVisible" destroy-on-close>
      <CreateDict v-if="['created','update','info'].includes(dialog.active)" :emit-data="currentSelected" @handleBoxEvent="handleDialog" />
      <DictCreate v-if="['dicTypeCreate','dicTypeEdit'].includes(dialog.active)" :emit-data="currentItem" @handleBoxEvent="handleDialog" />
    </el-dialog>
  </div>
</template>

<script>
import pageBtn from '@/views/mixin/pageBtn'
import CreateDict from './widget/CreateDict'
import DictCreate from './widget/CreateType'
import JTable from '@/components/JTable'

import {
  dictTypeTree, getListByType, getDict, createDic, removeDic, findChildrenDic,
  getDictType, createDictType, removeDictType, updateDictType
} from '@/api/dictionaries'
import { mapState } from 'vuex'
export default {
  components: {
    CreateDict,
    DictCreate,
    JTable
  },
  mixins: [pageBtn],
  props: {},
  data() {
    const listQuery = {
      total: 0,
      page: 1,
      size: 10,
      handleFilter: this.getList
    }
    const dialog = {
      dialogVisible: false,
      title: {
        created: '创建参数',
        update: '修改参数',
        info: '字典详情',
        dicTypeCreate: '字典类型添加',
        dicTypeEdit: '字典类型修改'
      },
      active: ''
    }
    return {
      listQuery,
      dialog,
      ditTypeInfo: {},
      listLoading: false,
      dataList: [],
      originType: [],
      parentId: -1,
      currentSelectedTree: {},
      currentSelected: {},
      currentItem: {},
      tableConfig: {
        listLoading: false,
        loadingText: '没数据',
        pagination: listQuery,
        tableAttribute: {
          'row-key': 'id',
          'tree-props': { children: 'children', hasChildren: 'hasChildren' }
        },
        thead: [
          {
            type: 'selection'
          },
          {
            type: 'index',
            label: '-',
            start: 1
          },
          {
            prop: 'name',
            label: '字典',
            width: 200,
            align: 'left'
          },
          {
            prop: 'code',
            label: 'code'
          },
          {
            prop: 'dictTypeCode',
            label: 'dictTypeCode'
          },
          {
            prop: 'dictLevel',
            label: 'dictLevel'
          },
          {
            prop: 'note',
            label: 'note'
          },
          {
            prop: 'status',
            label: 'status'
          },
          {
            prop: '',
            label: 'Actions',
            type: 'actions',
            width: '230',
            align: 'center'
          }
        ],
        search: ['allRole_eq', 'scopeCode', 'scopeName', 'scopeType_eq'],
        activeBox: {
          btnRules: { created: '/core/dict/saveDict', rulesFuntion: this.$_permisson }, // 按btn个数重左向右
          bindDefaultEvent: () => this.showDialog()
        }
      }
    }
  },
  computed: {
    ...mapState('user', { tenantCode: (state) => state.tenantCode }),
    options() {
      const result = this.originType
      return result
    },
    tableList() {
      const origin = this.dataList
      return origin
    }
  },
  watch: {},
  created() {
    this.getList()
  },
  mounted() {},
  methods: {
    handleTypeCreated() {
      this.setCurrentID()
      this.showDialog('dicType')
    },
    editTypeItem() {
      const { id } = this.currentSelectedTree
      getDictType(id).then(res => {
        const { data, code } = res
        if (code === 200) {
          this.currentItem = data
          // this.handleCreated('info')
          // this.currentItem = this.currentSelectedTree
          this.showDialog('dicTypeEdit')
        }
      })
    },
    handleActive(target = {}, type) {
      const { id } = target
      if (type === 'info') {
        getDict(id).then(res => {
          console.log('字典详情', res)
        })
      }

      if (type === 'edit') {
        this.currentSelected = target
        this.$nextTick(() => {
          this.showDialog('update')
        })
      }

      if (type === 'create') {
        if (!this.currentSelectedTree.key) {
          this.hiddenDialog()
          return this.$message('请选者要操作的根节点')
        }
        this.parentId = id
        this.showDialog()
      }
      if (type === 'del') {
        this.removeItem(id)
      }
    },
    load(tree, treeNode, resolve) {
      const { id } = tree
      findChildrenDic({ parentId: id }).then(res => {
        const { code, data } = res
        if (code === 200) {
          resolve(data)
        }
      })
    },
    removeItem(ids) {
      this.$confirm('此操作不可逆转, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        removeDic(ids).then(res => {
          const { code, message } = res
          if (code === 200) {
            this.$message({
              message,
              type: 'success'
            })
            this.getDic()
            return
          }
          this.$message.error(message)
        })
      })
    },
    handleFilter() {},
    showDialog(target = 'created') {
      this.dialog.dialogVisible = true
      this.dialog.active = target
    },
    hiddenDialog() {
      this.dialog.dialogVisible = false
      this.currentSelectedTree = {}
      this.currentId = null
      this.parentId = -1
      this.currentItem = {}
    },
    handleDialog(emit) {
      const { target } = emit
      if (!target) {
        return this.hiddenDialog()
      }

      const currentActive = this.dialog.active
      if (currentActive === 'created') {
        let parentId = this.parentId
        const tenantCode = this.tenantCode
        const dictTypeCode = this.currentSelectedTree.key

        if (this.currentSelected.id) parentId = this.currentSelected.id

        this.saveData({ ...target, parentId, tenantCode, dictTypeCode })
      }
      if (currentActive === 'update') {
        this.saveData({ ...this.currentSelected, ...target })
      }

      if (currentActive === 'dicTypeCreate') {
        const parentId = this.currentSelectedTree.id || -1
        const tenantCode = this.tenantCode
        this.saveTypeData({ ...target, parentId, tenantCode })
        return
      }
      if (currentActive === 'dicTypeEdit') {
        updateDictType({ ...this.currentItem, ...target }).then(res => {
          const { code, message } = res
          if (code === 200) {
            this.$message({
              message,
              type: 'success'
            })
            this.getList()
            return
          }
          this.$message.error(message)
        })
      }
    },
    saveTypeData(dictObj) {
      dictObj.delEnabled = dictObj.delEnabled ? 'Y' : 'N'
      createDictType(dictObj).then(res => {
        const { code, message } = res
        if (code === 200) {
          this.$message({
            message,
            type: 'success'
          })
          this.getList()
          this.hiddenDialog()
          return
        }
        this.$message.error(message)
      })
    },
    createTypeChildren(data) {
      this.currentSelectedTree = data
      this.showDialog('dicTypeCreate')
    },
    removeTypeItem(data) {
      this.$confirm('此操作不可逆转, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        const { id } = data
        removeDictType(id).then(res => {
          const { code, message } = res
          if (code === 200) {
            this.$message({
              message,
              type: 'success'
            })
            this.getList()
            this.hiddenDialog()
            return
          }
          this.$message.error(message)
        })
      })
    },
    saveData(dictObj) {
      if (dictObj) {
        createDic(dictObj).then(res => {
          const { code, message } = res
          if (code === 200) {
            this.$message({
              message,
              type: 'success'
            })
            this.hiddenDialog()
            this.getDic()
            return
          }
          this.$message.error(message)
        })
      }
    },
    getList(args = {}) {
      const { page: pageNum = 1, size: pageSize = 10, ...param } = args
      const params = { pageNum, pageSize, ...param }
      dictTypeTree(params).then(
        res => {
          const { code, data } = res
          if (code === 200) {
            this.originType = data
          }
        }
      )
    },
    /**
     * @description: 获取字典
     * @param {*} type 字典类型
     * @return {*}
     */
    getDic() {
      const { page, size } = this.listQuery
      const { key: type } = this.currentSelectedTree
      getListByType({ dictTypeCode: type, page, size }).then(res => {
        const { code, data: { list, total }} = res
        if (code === 200) {
          this.dataList = list
          this.listQuery.total = total
        }
      })
    },
    getDictTypeInfo() {
      const { id } = this.currentSelectedTree
      getDictType(id).then(res => {
        const { data, code } = res
        if (code === 200) {
          this.ditTypeInfo = data
        }
      })
    },
    handleNodeClick(data) {
      this.currentSelectedTree = data
      this.getDictTypeInfo()
      this.getDic()
    }
  }
}
</script>
<style lang="scss" scoped>
.wrapper{
   padding: 0px;
   margin: 0px;

  .aside{
    height: 100%;
    overflow: hidden;
    padding: 10px;
    background: #fff;
    border-radius: 8px;
    box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
    &>button{
      width: 100%;
      margin-bottom: 10px;
    }
    .treeItem{
      width: 100%;
      margin: 5px 0;
      // float: right;
    }

  }

   .main{
     padding-top: 0;
     overflow: hidden;
   }
   .dicBox{
     line-height: 1.5rem;
     box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
     margin: 10px 0;
     &>*{
       margin: 5px 0;
     }
   }
    .title{
      font-weight: bold;
      height: 2rem;
      line-height: 2rem;
    }
}
</style>
